/**
 * @file       nd03.c
 * @brief      二次封装库
 * @copyright  Copyright (c) 2020~2030 ShenZhen Dxtc Tech. Co., Ltd.
 * All rights reserved.
 * @version    V1.0
 * @author     TianXubin
 * @date       2022-08-15 15:30:18
 * @note       鼎新同创·智能锁
 *
 *****************************************************************************/

#include <string.h>
#include <stdlib.h>
#include "device.h"
#include "component.h"
#include "nd03b_platform.h"
#include "./ND03B/lib/nd03b_comm.h"
#include "./ND03B/lib/nd03b_dev.h"
#include "./ND03B/lib/nd03b_data.h"
#include "./ND03B/lib/nd03b_calib.h"
#include "./ND03B/lib/nd03b_def.h"

ND03B_Dev_t g_nd03b_device = {
    .i2c_dev_addr = ND03B_DEFAULT_SLAVE_ADDR,
    .SetXShutPinLevelFunc = set_xshut_pin_level,
    .GetGpio0PinLevelFunc = NULL,
};

static uint8_t test_mode = 0;

/**
  * @brief  模组是否存在
  * @note
  * @return int32_t
  */
int32_t ND03B_IsValid(void)
{
    return i2c_link_check(ND03B_DEFAULT_SLAVE_ADDR);
}

/**
  * @brief  设置工作模式
  * @note
  * @return int32_t
  */
int32_t ND03B_SetWorkMode(uint8_t mode)
{
    test_mode = mode;
    return 0;
}

/**
  * @brief  xtalk校准
  * @note
  * @return int32_t
  */
int32_t ND03B_Calibration_XTalk(void)
{
    return ND03B_XTalkCalibration(&g_nd03b_device);
}

/**
  * @brief  offset校准
  * @note
  * @return int32_t
  */
int32_t ND03B_Calibration_Offset(void)
{
    return ND03B_OffsetCalibration(&g_nd03b_device);
}

/**
  * @brief  开始捕获
  * @note
  * @return int32_t
  */
int32_t ND03B_StartCapture(void)
{
    int32_t ret = ND03B_ERROR_NONE;
    if (test_mode)
    {
        ret |= ND03B_HighRangingModeTrig(&g_nd03b_device);
    }
    else
    {
        ret |= ND03B_AutoDetectModeTrig(&g_nd03b_device);
    }
    return ret;
}

/**
  * @brief  读距离
  * @note
  * @param  ps：距离
  * @param  cfi：可信度
  * @return int32_t
  */
int32_t ND03B_ReadDistance(uint16_t *ps, uint8_t *cfi)
{
    int32_t ret = ND03B_ERROR_NONE;
    ND03B_RangingData_t data;

    ret |= ND03B_GetRangingData(&g_nd03b_device, &data);
    ND03B_Sleep(&g_nd03b_device);
    *ps = data.depth;
    *cfi = ((data.amp > 0xfe) ? 0xfe : (uint8_t)data.amp);
    NX_PRINTF("depth:%d mm, amp:%d\r\n", data.depth, data.amp);
    return ret;
}

/**
  * @brief  驱动库初始化
  * @note
  * @return int32_t
  */
void ND03B_DrvInit(void)
{
    /* 函数指针结构体 */
    ND03B_Func_Ptr_t dev_op = {NULL, NULL, NULL, NULL};

    /* 初始化函数指针结构体 */
    dev_op.Delay10usFunc = delay_10us;
    dev_op.Delay1msFunc = delay_1ms;
    dev_op.I2C_ReadNBytesFunc = i2c_read_nbytes;
    dev_op.I2C_WriteNBytesFunc = i2c_write_nbytes;

    /* 将host端功能函数注册到SDK中 */
    ND03B_RegisteredPlatformApi(dev_op);

    /* 初始化设备变量的IIC地址 */
    g_nd03b_device.i2c_dev_addr = ND03B_DEFAULT_SLAVE_ADDR;
}
